package com.szosen.measurement;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.szosen.bluetooth.BluetoothListActivity;
import com.szosen.bluetooth.BluetoothService;
import com.szosen.database.DBService;
import com.szosen.database.niaoye;
import com.szosen.device.GmpUa;
import com.szosen.device.GmpUa.UaRecord;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.jkzj.util.Contants;
import com.szosen.util.BackGroundThread;
import com.szosen.util.BackGroundThread.BackGroundTask;
import com.szosen.util.Cache;
import com.szosen.util.TimeHelper;
import com.szosen.util.ToastTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 尿液分析仪,可以测量 白细胞 亚硝酸盐 尿胆原 蛋白质 pH值 潜血 比重 酮体 胆红素 葡萄糖 维生素C 12个项目
 *
 */
public class MeasureUrine extends BaseActivity {

	private static TextView connect_status = null;// 蓝牙连接状态
	private static String btName = "EMP-UI";// 蓝牙名称
	private static String btMac = "";// 蓝牙mac
	private static Context context;
	private static Button uploadButton;// 上次数据按钮
	private static Button getDataButton;// 获取最新数据按钮
	private static Button findButton;// 查找设备按钮
	private static EditText leuEditText;
	private static EditText nitEditText;
	private static EditText ubgEditText;
	private static EditText proEditText;
	private static EditText phEditText;
	private static EditText sgEditText;
	private static EditText bldEditText;
	private static EditText ketEditText;
	private static EditText bilEditText;
	private static EditText gluEditText;
	private static EditText vcEditText;
	private static EditText dateEditText;

	private static ImageView imageView1;
	private static ImageView imageView2;
	private static ImageView imageView3;
	private String dataStr;

	private static final String TAG = "MeasureUrine";
	// private static final int UPLOADE_RESULT = 0x10245;
	OnClickListener clickListener;
	EditText user;
	String username;
	int userid;
	String token;
	private Cache cache;
	BluetoothServerSocket mBThServer = null;
	BluetoothSocket mBTHSocket = null;
	InputStream mmInStream = null;
	OutputStream mmOutStream = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.measure_urine);
		super.setTitleContent("【尿液测量】");
		myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		context = this;
		token = getIntent().getStringExtra("token");
		findViewid();
		cache = new Cache(context);
		if (token != null)
			uploadButton.setText("获取数据");
		setOnClickListener();// 设置监听器
		new Thread() {
			public void run() {
				System.out.println("马上开始连接。");
				connectBTFromStatic();
			};
		}.start();
		connThread();
	}

	private void connThread2() {
		readThread = new Thread() {
			public void run() {
				while (isReadData) {
					// TimeUnit.MILLISECONDS.sleep(100);
					try {
						byte[] first = null;
						byte[] second = null;
						if (mmInStream != null && mmInStream.available() > 0) {
							byte[] readBuf = new byte[512];
							int bytes;
							bytes = mmInStream.read(readBuf);
							if (bytes == 14) {
								first = new byte[bytes];
								// 复制first数组
								System.arraycopy(readBuf, 0, first, 0, bytes);
								Log.i(TAG,
										"getdata获取到蓝牙的数据。:"
												+ Arrays.toString(first));
								bytes = mmInStream.read(readBuf);
								if (bytes == 5) {
									second = new byte[bytes];
									System.arraycopy(readBuf, 0, second, 0,
											bytes);
									// 只需要有效的数据
									byte[] contentData = new byte[first.length
											+ second.length];// 只传递有效数据内容
									System.arraycopy(first, 0, contentData, 0,
											first.length);
									System.arraycopy(second, 0, contentData,
											first.length, second.length);
									Log.i(TAG,
											"getdata获取到有用的蓝牙的数据。:"
													+ Arrays.toString(first));
									SparseArray<List<byte[]>> map = GmpUa
											.getLegalPatternsFromBuffer(contentData);
									int dataSize = map.size();
									for (int i = 0; i < dataSize; i++) {
										int token = map.keyAt(i);// 获取token
										List<byte[]> datas = map.get(token);
										switch (token) {
										case GmpUa.TOKEN_SINGLE_DATA:
											// 把原来的数据都清空了。
											final GmpUa.UaRecord record = GmpUa
													.parseRecord(datas
															.get(datas.size() - 1));
											runOnUiThread(new Runnable() {
												public void run() {
													if (null == record) {
														Toast.makeText(
																context,
																"无存储数据",
																Toast.LENGTH_LONG)
																.show();
													} else {
														showRecord(record);// 显示记录
														uploadAuto();
													}
												}
											});
										}
									}
									first = null;
									second = null;
								}
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			};
		};
		readThread.start();
	}

	private void connThread() {
		readThread = new Thread() {
			public void run() {
				while (isReadData) {
					read();
				}
			};
		};
		readThread.start();
	}
	private void read(){
		int tryTime = 2;
		try {
			while (mmInStream.available() <= 0 && (tryTime--) >= 0)
				TimeUnit.MILLISECONDS.sleep(100);
			if (tryTime < 0)// 睡一觉起来，蓝牙通道都管了，还读啥呀,回去!
				return;
			byte[] buffer = new byte[256];
			int bytes;
			bytes = mmInStream.read(buffer);
			if (bytes <= 0)
				return;
			byte[] contend = new byte[bytes];// 只传递有效数据内容
			for (int i = 0; i < bytes; i++) {
				contend[i] = buffer[i];
			}
			handler.obtainMessage(BluetoothService.MESSAGE_READ,
					bytes, -1, contend).sendToTarget();// 传递给界面更新数据
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case BluetoothService.MESSAGE_STATE_CHANGE:
				switch (msg.arg1) {
				case BluetoothService.STATE_CONNECTED:
					connect_status.setText("已连接" + btName + "");
					connect_status.setTextColor(Color.BLUE);
					setVisibility();// 设置测量按钮可见
					break;
				case BluetoothService.STATE_CONNECTING:
					connect_status.setText(R.string.connecting);
					connect_status.setTextColor(Color.BLUE);
					setVisibility();
					break;
				case BluetoothService.STATE_NONE:
					// 设备未连接。
					try {
						System.out.println("尿液执行重连。。。");
						// connectGmpUa();
					} catch (Exception e) {
					}
					connect_status.setText(R.string.unconnect);
					connect_status.setTextColor(Color.RED);
					setVisibility();
					break;
				}
				break;

			case BluetoothService.MESSAGE_WRITE:
				byte[] writeBuf = (byte[]) msg.obj;
				new String(writeBuf);
				// Toast.makeText(context,
				// writeMessage,
				// Toast.LENGTH_LONG).show();
				break;
			case BluetoothService.MESSAGE_READ:
				byte[] readBuf = (byte[]) msg.obj;
				Log.i(TAG, "get得到了蓝牙的数据:" + Arrays.toString(readBuf));
				SparseArray<List<byte[]>> map = GmpUa
						.getLegalPatternsFromBuffer(readBuf);
				int dataSize = map.size();
				for (int i = 0; i < dataSize; i++) {
					int token = map.keyAt(i);// 获取token
					List<byte[]> datas = map.get(token);
					switch (token) {
					case GmpUa.TOKEN_SINGLE_DATA:
						GmpUa.UaRecord record = GmpUa.parseRecord(datas
								.get(datas.size() - 1));
						if (null == record) {
							Toast.makeText(context, "无存储数据", Toast.LENGTH_LONG)
									.show();
						} else {
							showRecord(record);// 显示记录
							uploadAuto();
						}
					}
				}
				break;
			case BluetoothService.MESSAGE_TOAST:
				Toast.makeText(context,
						msg.getData().getString(BluetoothService.TOAST),
						Toast.LENGTH_SHORT).show();
				break;
			case BluetoothService.MESSAGE_DEVICE:
				btName = msg.getData().getString(BluetoothService.DEVICE_NAME);
				String address = msg.getData().getString(
						BluetoothService.DEVICE_ADDRESS);
				cache.saveDeviceAddress(Cache.GMPUA, address);// 保存地址,以便下次自带连接
				break;
			case 9:
				ToastTool.showLong(context, "没有网络连接，离线保存");
				break;
			}
		}
	};

	public void connnectDeviceAgain(View view) {
		if (this.connect_status.getText().toString().trim().equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS)) {
			ToastTool.showShort(context, Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS_NOTCONNECTAGAIN);
			return;
		}
		new Thread() {
			public void run() {
				connectBTFromStatic();
			};
		}.start();
	}

	boolean isReadData = true;

	@Override
	@SuppressLint("ResourceAsColor")
	protected void onResume() {
		super.onResume();
	}

	public static class PersistWriter extends Thread {
		private BluetoothService bluetoothService;
		private static final String TAG = "PC300.PersistWriter";
		private byte[] command;// 传递的命令
		private long sleepTime;// 间隔时间
		private OutputStream os = null;

		public PersistWriter(OutputStream os, byte[] command, long sleepTime) {
			this.os = os;
			this.bluetoothService = bluetoothService;
			this.command = command;
			this.sleepTime = sleepTime;
		}

		public static boolean isStart = true;

		@Override
		public void run() {
			while (isStart) {
				try {
					if (os != null) {
						os.write(command);// 电量命令
					}
					TimeUnit.MILLISECONDS.sleep(sleepTime);// 每隔一段时间发送一次电量查询命令
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 设置监听器
	 */
	private void setOnClickListener() {
		clickListener = new OnClickListener() {
			@Override
			public void onClick(View view) {
				if (view == getDataButton) {
					sendCommd(GmpUa.COMMAND_SINGLE_DATA);
					uploadButton.setEnabled(true);// 获取数据后才能上传数据
				} else if (view == findButton) {
					startDeviceListActivity();// 开启查找蓝牙activity
				} else if (view == uploadButton) {
					uploadAuto();
				}
			}
		};
		uploadButton.setOnClickListener(clickListener);
		getDataButton.setOnClickListener(clickListener);
		findButton.setOnClickListener(clickListener);
	}

	/**
	 * 发送命令
	 *
	 * @param command
	 */
	private void sendCommd(byte[] command) {
		Log.i(TAG, "send蓝牙数据:" + Arrays.toString(command));
		// 发送获取数据的命令
		if (mmOutStream != null) {
			try {
				mmOutStream.write(command);
				// 发送了一条命令
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/* 自动上传 */
	private void uploadAuto() {
		// uploadButton.setEnabled(false);// 按钮不可用，避免多次上传
		try {
			upload();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// Toast.makeText(context, "后台开始上传", Toast.LENGTH_SHORT).show();
		if (token != null) {
			Intent intent = getIntent();
			intent.putExtra("data", dataStr);
			setResult(13, intent);
			finish();
		}
	}

	// 自动连接蓝牙功能。
	private void connectBTFromStatic() {
		btHandler.obtainMessage(WHAT_CONNECTING).sendToTarget();
		btMac = cache.getDeviceAddress(Cache.GMPUA);
		if (TextUtils.isEmpty(btMac)) {
			//设备无绑定
			btHandler.obtainMessage(WHAT_CONNECTNOBOND).sendToTarget();
			return;
		} else if (connect_status.getText().toString()
				.equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS)) {
			closeBT();
		}
		BluetoothDevice btDev = myBluetoothAdapter.getRemoteDevice(btMac);
		connectDevice(btDev);
		System.out.println("正在自动连接蓝牙设备！！！");
	}

	protected void upload() throws JSONException {
		String leu = leuEditText.getText().toString();
		if (TextUtils.isEmpty(leu)) {
			ToastTool.showShort(context, "请先开始测量！");
			return;
		}
		niaoye niaoyeBean = new niaoye();
		niaoyeBean.setIdCard(BaseActivity.getIdCard());
		niaoyeBean.setLeu(leuEditText.getText().toString());
		niaoyeBean.setNit(nitEditText.getText().toString());
		niaoyeBean.setUbg(ubgEditText.getText().toString());
		niaoyeBean.setPro(proEditText.getText().toString());
		niaoyeBean.setPh(phEditText.getText().toString());
		niaoyeBean.setSg(sgEditText.getText().toString());
		niaoyeBean.setBld(bldEditText.getText().toString());
		niaoyeBean.setKet(ketEditText.getText().toString());
		niaoyeBean.setBil(bilEditText.getText().toString());
		niaoyeBean.setGlu(gluEditText.getText().toString());
		niaoyeBean.setVc(vcEditText.getText().toString());
		niaoyeBean.setTime(dateEditText.getText().toString().replace("/", "-"));
		boolean b = DBService.add(niaoyeBean);
		if (b) {
			ToastTool.showLong(context, "数据保存成功");
		} else {
			ToastTool.showLong(context, "数据保存成功");
		}
	}

	/**
	 * 初始化控件
	 */
	private void findViewid() {
		imageView1 = (ImageView) findViewById(R.id.urine_status_image1);
		imageView2 = (ImageView) findViewById(R.id.urine_status_image2);
		imageView3 = (ImageView) findViewById(R.id.urine_status_image3);
		uploadButton = (Button) findViewById(R.id.upload_button);
		getDataButton = (Button) findViewById(R.id.get_data_button);
		leuEditText = (EditText) findViewById(R.id.leu);
		nitEditText = (EditText) findViewById(R.id.nit);
		ubgEditText = (EditText) findViewById(R.id.ubg);
		proEditText = (EditText) findViewById(R.id.pro);
		phEditText = (EditText) findViewById(R.id.pH);
		sgEditText = (EditText) findViewById(R.id.sg);
		bldEditText = (EditText) findViewById(R.id.bld);
		ketEditText = (EditText) findViewById(R.id.ket);
		bilEditText = (EditText) findViewById(R.id.bil);
		gluEditText = (EditText) findViewById(R.id.glu);
		vcEditText = (EditText) findViewById(R.id.vc);
		dateEditText = (EditText) findViewById(R.id.measure_time);
		connect_status = (TextView) findViewById(R.id.connect_status);
		findButton = (Button) findViewById(R.id.find_device);
		connect_status.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
		connect_status.setTextColor(Color.BLUE);
		dateEditText.setText(TimeHelper.getCurrentTime());
	}

	@Override
	public void onBackPressed() {
		// 尿液
		String connectStatus = connect_status.getText().toString();
		if (connectStatus
				.equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING)) {
			ToastTool.showLong(context, "正在连接设备，请勿退出!");
		} else {
			super.onBackPressed();
		}
		// super.onBackPressed();
		isReadData=false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		closeBT();
		isReadData = false;
		finish();
	}

	/***
	 * 关闭蓝牙通道。
	 */
	private void closeBT() {
		try {
			if (mBTHSocket != null) {
				// 不为空，就获取输入输出流，
				mBTHSocket.close();
				// mmOutStream = mBTHSocket.getOutputStream();
				// mmInStream = mBTHSocket.getInputStream();
			}
			if (mBThServer != null) {
				mBThServer.close();
			}
			if (mmOutStream != null) {
				mmOutStream.close();
			}
			if (mmInStream != null) {
				mmInStream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 开启查找蓝牙设备的activity
	 */
	private void startDeviceListActivity() {
		Intent serverIntent = new Intent(this, BluetoothListActivity.class);
		// 如果已经连接。就不显示未绑定的蓝牙了
		// 如果没有已经绑定的，就是为空了。那就绑定其他的了
		serverIntent.putExtra("tag", "EMP_Ui");
		startActivityForResult(serverIntent,
				BluetoothListActivity.REQUEST_CONNECT_DEVICE);
	}

	UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	BluetoothAdapter myBluetoothAdapter = null;

	private boolean connectDevice(BluetoothDevice device) {
		try {
			if (!myBluetoothAdapter.isEnabled()) {
				myBluetoothAdapter.enable();
			}
			// Intent discoverableIntent = new Intent(
			// BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//
			// 使得蓝牙处于可发现模式，持续时间150s
			// discoverableIntent.putExtra(
			// BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
			// mBTHSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
			// int sdk = Integer.parseInt(Build.VERSION.SDK);
			// if (sdk >= 10) {
			// mBTHSocket = device
			// .createInsecureRfcommSocketToServiceRecord(MY_UUID);
			// } else {
			// mBTHSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
			// }

			myBluetoothAdapter.cancelDiscovery();

			mBTHSocket = device
					.createInsecureRfcommSocketToServiceRecord(MY_UUID);
			mBThServer = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(
					"myServerSocket", MY_UUID);
			mBTHSocket.connect();
			mmInStream = mBTHSocket.getInputStream();
			mmOutStream = mBTHSocket.getOutputStream();
		} catch (IOException e) {
			btHandler.obtainMessage(WHAT_CONNECTHAND).sendToTarget();
			return false;
		}
		if ((mmInStream != null) && (mmInStream != null)) {
			// 发送连接成功的handler
			// 保存连接的蓝牙地址
			cache.saveDeviceAddress(Cache.GMPUA, device.getAddress());
			btHandler.obtainMessage(WHAT_CONNECTSUCCESS).sendToTarget();
			Log.d("保存尿液的数据成功》》》", "success" + device.getAddress());
			return true;
		} else {
			return false;
		}
	}

	private final static int WHAT_CONNECTERROR = 44444;
	private final static int WHAT_CONNECTSUCCESS = 66666;
	private final static int WHAT_CONNECTHAND = 55555;
	private final static int WHAT_CONNECTING = 33333;
	private final static int WHAT_CONNECTNOBOND = 3;

	Handler btHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case WHAT_CONNECTERROR:
				// 连接蓝牙错误
				connect_status
						.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECT_NULL);
				connect_status.setTextColor(Color.RED);
				break;
			case WHAT_CONNECTSUCCESS:
				// 连接蓝牙成功。
				// 新建一个检测读取蓝牙的线程。
				connect_status
						.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS);
				connect_status.setTextColor(Color.BLUE);
				break;
			case WHAT_CONNECTHAND:
				connect_status
						.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
				connect_status.setTextColor(Color.RED);
				// ToastTool.showLongClear(mContext, "设备自动连接失败，请手动连接设备！");
				break;
			case WHAT_CONNECTING:
				connect_status
						.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
				connect_status.setTextColor(Color.BLUE);
				// ToastTool.showLongClear(mContext, "设备自动连接失败，请手动连接设备！");
				break;
				case WHAT_CONNECTNOBOND:
					connect_status
							.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECT_NOBOND);
					connect_status.setTextColor(Color.RED);
					// ToastTool.showLongClear(mContext, "设备自动连接失败，请手动连接设备！");
					break;
			}
		}
	};
	private Thread readThread;

	/**
	 * 设置几个button的显示与隐藏
	 *
	 */
	private static void setVisibility() {
	}

	/**
	 * 显示记录
	 *
	 * @param record
	 */
	public static void showRecord(UaRecord record) {
		leuEditText.setText(record.leu);
		nitEditText.setText(record.nit);
		ubgEditText.setText(record.ubg);
		proEditText.setText(record.pro);
		phEditText.setText(record.ph);
		sgEditText.setText(record.sg);
		bldEditText.setText(record.bld);
		ketEditText.setText(record.ket);
		bilEditText.setText(record.bil);
		gluEditText.setText(record.glu);
		vcEditText.setText(record.vc);
		dateEditText.setText(record.date);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case BluetoothListActivity.REQUEST_CONNECT_DEVICE:
			if (resultCode == Activity.RESULT_OK) {
				String address = data.getExtras().getString(
						BluetoothListActivity.EXTRA_DEVICE_ADDRESS);
				btMac = address;
				leuEditText.setText("");
				nitEditText.setText("");
				ubgEditText.setText("");
				proEditText.setText("");
				phEditText.setText("");
				sgEditText.setText("");
				bldEditText.setText("");
				ketEditText.setText("");
				bilEditText.setText("");
				gluEditText.setText("");
				vcEditText.setText("");
				dateEditText.setText("");
				Log.i("address蓝牙地址", btMac);
				BluetoothDevice btDev = myBluetoothAdapter
						.getRemoteDevice(address);
				connectDevice(btDev);
			}
			break;
		}
	}

	@SuppressLint("ResourceAsColor")
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			MeasureUrine.this.setResult(RESULT_OK);
			MeasureUrine.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void uploadInBack(final JSONObject data, final String path,
			final ContentValues values) {
		new BackGroundThread(new BackGroundTask() {

			@Override
			public void process() {
			}
		}).start();
	}
}
